package com.hooper.dp.aop;

import com.hooper.dp.anno.TokenIgnore;
import com.hooper.dp.dto.UserDTO;
import com.hooper.dp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/02/25/14:25
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //过滤不需要token验证的方法，如发送验证码，登录，首页等
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = ((HandlerMethod) handler);
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(TokenIgnore.class)) {
                return true;
            }
        }
        UserDTO user = UserHolder.getUser();
        if (user == null){
            response.setStatus(401);
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

}
